package ldh.im.fxgui.component.cell;

import com.jfoenix.controls.JFXDialog;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import ldh.im.dto.enums.MessageType;
import ldh.im.fxbase.dao.ImCollectDao;
import ldh.im.fxbase.data.pojo.ImCollect;
import ldh.im.fxbase.data.pojo.ImGroup;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.data.pojo.status.ImCollectContent;
import ldh.im.fxbase.data.pojo.status.ImMessageRefType;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.controller.CollectController;
import ldh.im.fxgui.controller.sub.TransferMessageController;
import ldh.im.fxgui.pane.MessagePane;
import ldh.im.fxgui.pane.MessagePaneEnum;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.util.DateUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏ListCell
 */
public class CollectView extends StackPane {

    private ImCollect imCollect;
    private ImMessage imMessage;
    private VBox container = new VBox();
    private Pane popupPane = null;

    private CollectController collectController;

    public CollectView(CollectController collectController, ImCollect imCollect) {
        this.collectController = collectController;

        this.getStyleClass().add("collect-view");
        container.getStyleClass().add("collect-container");
        this.getChildren().add(container);
        container.setAlignment(Pos.CENTER_LEFT);
        this.imCollect = imCollect;

        initUi();

        this.setOnMouseClicked(e->{
            if (e.getButton() != MouseButton.SECONDARY) return;
            if (popupPane == null) {
                popupPane = createPopupPane();
            }
            UiUtil.getMainPopup().getContent().setAll(popupPane);
            UiUtil.getMainPopup().show(this.getScene().getWindow(), e.getScreenX(), e.getScreenY());
        });
    }

    private void initUi() {
        ImCollectContent collectContent = imCollect.getCollectContent();
        List<ImCollectContent> refCollectContents = collectContent.getRefCollectContents();
        MessageType messageType = collectContent.getMessageType();

        imMessage = collectContent.toMessage();
        imMessage.setCurrentUserId(imCollect.getUserId());
        if (refCollectContents != null) {
            MessagePane messagePane = MessagePaneEnum.getByMessageType(messageType).getMessagePane();
            Node node = messagePane.createCollectPane(imMessage);
            VBox vBox = new VBox();
            vBox.getChildren().addAll(node);

            List<ImMessage> refMessages = imMessage.getRefMessages();
            if (refMessages == null) {
                refMessages = new ArrayList<>();
                imMessage.setRefMessages(refMessages);
            }

            for (ImCollectContent refCollectContent : refCollectContents) {
                ImMessage imMessage = refCollectContent.toMessage();
                refMessages.add(imMessage);
                Node refNode = MessagePaneEnum.getByMessageType(imMessage.getMessageType()).getMessagePane().createCollectPane(imMessage);
                vBox.getChildren().add(refNode);
            }

            String refMessageIds = refMessages.stream().map(ImMessage::getServerId).collect(Collectors.joining(","));
            imMessage.setRefMessageIds(refMessageIds);
            imMessage.setRefType(ImMessageRefType.ref);

            container.getChildren().add(vBox);
        } else {
            MessagePane messagePane = MessagePaneEnum.getByMessageType(messageType).getMessagePane();
            Node node = messagePane.createCollectPane(imMessage);
            container.getChildren().add(node);
        }

        container.getChildren().add(buildNamePane(imMessage));
    }

    private Pane createPopupPane() {
        VBox vBox = new VBox();
        vBox.getStyleClass().add("collect-pop-pane");
        vBox.getChildren().add(RegionUtil.createButton("转发", this::transfer));           // 转发
        vBox.getChildren().add(RegionUtil.createButton("选择标签", this::selectLabel));    // 选择标签
//        vBox.getChildren().add(RegionUtil.createButton("多选", this::manySelect));           // 多选

        vBox.getChildren().add(new Separator());

        if (imCollect.getMessageType() == MessageType.Image) {
            vBox.getChildren().add(RegionUtil.createButton("复制", this::copy));           // 复制
        }
        vBox.getChildren().add(RegionUtil.createButton("删除", this::delete));             // 删除
        return vBox;
    }

    private Node buildNamePane(ImMessage message) {
        HBox hBox = new HBox();
        Label nameLabel = new Label();
        nameLabel.getStyleClass().add("name-label");

        if (message.isGroup()) {
            ImGroup group = ImCacheFactory.getInstance().getImGroup(message.getCurrentUserId(), message.getGroupCode());
            if (group != null) {
                nameLabel.setText(group.getName());
            }
        } else {
            ImUser imUser = ImCacheFactory.getInstance().getUser(message.getFromUserId());
            if (imUser != null) {
                nameLabel.setText(imUser.getUserName());
            }
        }
        Region region = new Region();
        HBox.setHgrow(region, Priority.ALWAYS);

        Label timeLabel = new Label();
        timeLabel.getStyleClass().add("time-label");

        Date createDate = imCollect.getCreateTime();
        if (DateUtil.isToday(createDate)) {
            timeLabel.setText("今天");
        } else {
            timeLabel.setText(DateUtil.format(createDate, "yyyy年MM月dd日"));
        }

        hBox.getChildren().addAll(nameLabel, region, timeLabel);
        return hBox;
    }

    private void transfer(ActionEvent actionEvent) {
        RegionUtil.FxmlBean<Pane, TransferMessageController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/sub/TransferMessagePane.fxml"));
        JFXDialog dialog = DialogUtil.show(fxmlBean.getNode(), false);

        fxmlBean.getController().setDialog(dialog);
        fxmlBean.getController().setTransferImages(Arrays.asList(imMessage), true);
        UiUtil.getMainPopup().hide();
    }

    private void selectLabel(ActionEvent actionEvent) {
        // todo
    }

    private void manySelect(ActionEvent actionEvent) {
        // todo
    }

    private void copy(ActionEvent actionEvent) {
        UiUtil.getMainPopup().hide();
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();
        content.putImage(new Image(FileUtil.getFilePath(imMessage)));
        clipboard.setContent(content);
    }

    private void delete(ActionEvent actionEvent) {
        Task<Boolean> task = new Task() {

            @Override
            protected Object call() throws Exception {
                ImCollectDao imCollectDao = BeanFactory.getInstance().getBean(ImCollectDao.class);
                imCollectDao.deleteById(imCollect.getId());
                return true;
            }
        };
        ThreadPoolUtil.submitTask(task);
        task.setOnSucceeded(s->{
            collectController.remove(imCollect);
        });
    }

}
